const router = require('express').Router()
const { code2AccessToken, refreshToken } = require('../../tsp/oauth-server/index')

router.post('/token', (req, res) => {
  console.log(`OAuth Server invoked. ${JSON.stringify(req.body)}`)
  doHandle(req.body).then(data => {
    res.send(data)
  })
})

function doHandle({ grant_type, refresh_token, code, client_id, client_secret, redirect_uri }) {
  switch (grant_type) {
    case 'authorization_code': {
      return code2AccessToken({ grant_type, code, client_id, client_secret, redirect_uri })
    }
    case 'refresh_token': {
      return refreshToken({ grant_type, refresh_token, client_id, client_secret })
    }
    default: {
      throw new Error(`grant_type is invalid: ${grant_type}`)
    }
  }
}

module.exports = router
